<?php

class PublicController extends Controller {

    public $renderLogin = true;

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
// captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
            'uploadResource' => array(
                'class' => 'application.actions.site.XUploadResourceAction',
                'path' => Yii::app()->getBasePath() . "/../files",
                'publicPath' => Yii::app()->getBaseUrl() . "/files",
                'subfolderVar' => "parent_id",
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        if (Yii::app()->user->isGuest)
            $this->actionLogin();
    }

    /**
     * This is the action to handle external excepiftions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $activationKey = Yii::app()->request->getQuery('activationKey');
        if ($activationKey != NULL)
            $this->actionActivate();
        else
            Blyn::app()->getAppUI()->renderLogin();
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionMessage($msg) {
        $this->render('message', array('message' => $msg));
    }

    public function actionActivate() {

        $key = Yii::app()->request->getQuery('activationKey');
        $email = Yii::app()->request->getQuery('email');

        Blyn::app()->getAppUI()->activateUser($key, $email);
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                // need to allow captcha in order to view it.
                'actions' => array('index', 'login', 'create', 'captcha', 'activate'),
                'users' => array('*'),
            ),
        );
    }

    public function actionWeChatMeta() {
        if (isset($_GET["transaction_id_value"]) && isset($_GET["out_trade_no_value"])&& isset($_GET["userOpenid"]) &&  isset($_GET["jq_openid"]) && isset($_GET["totalCount"]) && isset($_GET["TotalMoney"])) {
            $transaction_id = $_GET["transaction_id_value"];
	    $out_trade_no = $_GET["out_trade_no_value"];
            $userOpenid = $_GET["userOpenid"];
            $jq_openid = $_GET["jq_openid"];
            $totalCount = $_GET["totalCount"];
            $TotalMoney = $_GET["TotalMoney"];
            $wchatSheet = new BSheet('wechatMeta', Blyn::app());
            $wchatSheet->addList(array("transaction_id" => $transaction_id, "out_trade_no" => $out_trade_no,"userOpenid"=>$userOpenid,"jq_openid"=>$jq_openid,"totalCount"=>$totalCount,"TotalMoney"=>$TotalMoney));
            //付款成功后，发送消息
 //           if(Blyn::app()->getActiveSpace()->getAttribute('wechat_appid')){
 //               if(Blyn::app()->getActiveSpace()->getAttribute('wechat_appsecret')){
                    $Appid = "wxfa9b2fff1a53ad4f";
                    $Appsecret = "31c92a765f5dd147f8821bcf51d296d8";
                    $WeChat = new BWeChatClass($Appid, $Appsecret);
                    $CommenMessage = '场地数量:'.$totalCount.'\n支付总金额:'.$TotalMoney.'元';
                    $Message = '恭喜，您已成功预定场地！\n'.$CommenMessage;
//                    $returnMsg = $WeChat->send_custom_message($userOpenid, "text", $Message);
                    $returnMsg = $WeChat->send_custom_message($jq_openid, "text", $Message);
                    //var_dump($returnMsg);
                    $result = json_decode($returnMsg, true);
                    if ($result["errcode"] == 0) {
                        $wchatSheet->addList(array("SendMessage" => "success"));
                        echo "send message ok";
                    }
                    $userInfo = $WeChat->get_user_info($jq_openid);
                    $nickname = $userInfo["nickname"];//昵称
                    //发送消息给管理员
                    $WeChatQy = new BWeChatQyClass("wx6b0b7108268af8e1", "N2HFYmf3ZuaGXumKo3x51xFxOnXxDnylq3mes7cun0YeUjZOT84XNEBvyUM-7oIB");
                    //echo $weixin->access_token;
                    $topartyID = 2;
                    $type = 'text';
                    $agent = 8;
                    $msgToAdmin = $nickname.'预定了一块场地\n'.$CommenMessage;//将此信息发送给管理员
                    $sendRes = $WeChatQy->sendMessageParty($topartyID, $type,$agent, $msgToAdmin);
                    $msgToAdminesult = json_decode($sendRes, true);
                    if ($msgToAdminesult["errcode"] == 0) {
                        $wchatSheet->addList(array("SendMessageToAdmin" => "success"));
                        echo "send message to admin ok";
                    }

//              }
//            }
            echo  "success";
        }
    }
    
    public function afterAction($action) {
        //parent::afterAction($action);
        Yii::app()->end();
    }

}
